// redis
import { createClient } from 'redis'

const redisClient = createClient({
  password: 'YGY1h4NEGzaPQZv5XJjb2NWUEJsRO4Eh',
  socket: {
    host: 'redis-14012.c302.asia-northeast1-1.gce.cloud.redislabs.com',
    port: 14012
  }
})

redisClient.on('connect', function () {
  console.log('redis 连接成功')
})
redisClient.on('error', function (err) {
  console.log('redis 连接异常 ', err)
})
redisClient.on('reconnecting', (stats) => {
  console.log('redis重连', stats)
})

function connect () {
  return redisClient.connect()
}

async function hSet (key, hashkey, hashval) {
  if (typeof hashval === 'object') {
    hashval = JSON.stringify(hashval)
  }
  await redisClient.hSet(key, hashkey, hashval)
}

function hGetAll (key) {
  return redisClient.hGetAll(key).then(val => {
    return Promise.resolve(val)
  }, (err) => {
    return Promise.reject(err)
  })
}

async function hDel (key, hashkey) {
  await redisClient.hDel(key, hashkey)
}

export default {
  connect,
  hSet,
  hGetAll,
  hDel
}
